package com.easyattendance.services;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.ClassUser;
import com.easyattendance.model.Section;
import com.easyattendance.model.Class;
import com.easyattendance.model.SubjectClass;
import com.easyattendance.model.SubjectTeacher;
import com.easyattendance.model.Teacher;
import com.easyattendance.util.HibernateUtil;
import com.sun.org.apache.bcel.internal.generic.GETSTATIC;

public class AddClassService {

	/* Method to CREATE a class in the database */
	   public synchronized boolean addClass(Class classes,ClassUser classuser){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         //classuser.setClassObj(classes);
	         classes.setClass_users(classuser);
	        
	         
        	 session.save(classes);
        	 session.save(classuser);
	        	 
	         tx.commit();
	         result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	     return result;
	   }
	   
	   /* Method to UPDATE a class in the database */
	   public synchronized boolean updateClass(Class classes,ClassUser classuser){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         classuser.setClassObj(classes);
	         classes.setClass_users(classuser);
	         
	        	 session.update(classes);
	        	 session.update(classuser);
	           	 tx.commit();
	           	 return true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	     return result;
	   }
	   
	   /* Method to DELETE an class from the records */
	   public synchronized boolean deleteClass(String classId){
		   Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean flag = false;
	      try{
	         tx = session.beginTransaction();
	         Class classs = (Class) session.createQuery("FROM Class where class_id='"+classId+"'").uniqueResult();
	         	session.delete(classs);
	         
	         tx.commit();
	         flag = true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return flag;
	   }
	   
	   public boolean ifAlreadyExists(String classId) {
			 boolean flag = getUserByUserId(classId);
			 
			 return flag;

		}
	   
	   public boolean ifAlreadyExists(Class newClass) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List classes = null;
		      try{
		         tx = session.beginTransaction();
		         classes = session.createQuery("FROM Class").list(); 
		         for (Iterator iterator = classes.iterator(); iterator.hasNext();){
		        	 Class tempClass = (Class) iterator.next(); 
		            if(tempClass.equals(newClass)) {
		            	System.out.println("Class already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
		}
	   
	   public boolean ifClassExists(String classId) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List classes = null;
		      try{
		         tx = session.beginTransaction();
		         classes = session.createQuery("FROM Class").list(); 
		         for (Iterator iterator = classes.iterator(); iterator.hasNext();){
		        	 Class tempclass = (Class) iterator.next(); 
		            if(tempclass.getClass_id().equals(classId)) {
		            	System.out.println("Class already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
		}
	   
	   
		public boolean getUserByUserId(String classId) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Class classes = null;
			 Query query=null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from Class where class_id='"+classId+"'");
				 List list = query.list();
				 			 
				 if (list.isEmpty()) {
					 flag = false;
				 }
				 else {
					 flag = true;
				 }
				 if (!tx.wasCommitted()) {
					 tx.commit();
				 }
					 
			 } catch (Exception e) {
				 if (tx != null) {
					 tx.rollback();
				 }
				 e.printStackTrace();
			 } finally {
				 session.close();
			 }
			return flag;
		}
		
		public Class getClassById(String classId) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Class classes = null;
			 Query query=null;
			 Class user = null;
			 
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from Class where class_id='"+classId+"'");
				 user = (Class) query.uniqueResult();
		            tx.commit();
		        } catch (Exception e) {
		            if (tx != null) {
		                tx.rollback();
		            }
		            e.printStackTrace();
		        } finally {
		            session.close();
		        }
		        return user;
		    }
		
		/* Get class_user by class id */
		public ClassUser getClassUserById(String classId) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Query query=null;
			 ClassUser user = null;
			 
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from ClassUser where class_id='"+classId+"'");
				 user = (ClassUser) query.uniqueResult();
		            tx.commit();
		        } catch (Exception e) {
		            if (tx != null) {
		                tx.rollback();
		            }
		            e.printStackTrace();
		        } finally {
		            session.close();
		        }
		        return user;
		    }
		
		public Class getClassByClassId_SectionEmail(String classId, String sectionEmail) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Class classes = null;
			 Query query=null;
			 Class user = null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				 query = session.createQuery("from Section where email_id='"+sectionEmail+"'");
				 Section section = (Section)query.uniqueResult();
				 query = session.createQuery("from Class where class_id='"+classId+"' and section_id='"+section.getSection_id()+"'");
				 user = (Class)query.uniqueResult();
		            tx.commit();
		        } catch (Exception e) {
		            if (tx != null) {
		                tx.rollback();
		            }
		            e.printStackTrace();
		        } finally {
		            session.close();
		        }
		        return user;
		    }
		
		public String getSectionByClassId(String classId)
		{
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Class classObj=null;
			 
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				 
				 Query query = session.createQuery("from Class where class_id='"+classId+"'");
				 classObj= (Class) query.uniqueResult();
		            tx.commit();
		        } catch (Exception e) {
		            if (tx != null) {
		                tx.rollback();
		            }
		            e.printStackTrace();
		        } finally {
		            session.close();
		        }
		        return classObj.getSection().getSection_id();
		}
		
		public List<Class> listClassBySectionId(String sectionId) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Class classes = null;
			 List<Class> list=null;
			 Class user = null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				 
				 list = session.createQuery("from Class where section_id='"+sectionId+"'").list();
				 
		            tx.commit();
		        } catch (Exception e) {
		            if (tx != null) {
		                tx.rollback();
		            }
		            e.printStackTrace();
		        } finally {
		            session.close();
		        }
		        return list;
		    }
		
		public String getClassIdByTeacherId(String teacherEmailId) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Class classes = null;
			 Query query=null;
			 Class user=null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from Teacher where email_id='"+teacherEmailId+"'");
				 Teacher teacher = (Teacher) query.uniqueResult();
				 String sectionId = teacher.getSection().getSection_id();
				 String teacherId = teacher.getTeacher_id();
				 query = session.createQuery("from Class where section_id='"+sectionId+"' and class_teacher_id='"+teacherId+"'");
				 user = (Class)query.uniqueResult();
				 
				/* for(Iterator iterator = query1.iterator(); iterator.hasNext(); ) {
					 SemYear temp = (SemYear) iterator.next();
					 System.out.println("sem year: "+ temp.getSem_year_id());
				 } */
				 
				 tx.commit();
		        } catch (Exception e) {
		            if (tx != null) {
		                tx.rollback();
		            }
		            e.printStackTrace();
		        } finally {
		            session.close();
		        }
		        return user.getClass_id();
		    }
	   
		/* Method to  READ all the class values */
		   public List listClasses( ) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List classes = null;
		      try{
		         tx = session.beginTransaction();
		         classes = session.createQuery("FROM Class").list(); 
		         for (Iterator iterator =classes.iterator(); iterator.hasNext();){
		        	Class tempclass = (Class) iterator.next(); 
		            System.out.print("ClassId: " + tempclass.getClass_id()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return classes;
		   }
		   
		   /* Method to  READ all the class values of particular section */
		   public List<Class> listClasses(String currentUser) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Class> classes = null;
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("from Section where email_id='"+currentUser+"'");
		         Section user = (Section)query.uniqueResult();
		         classes = session.createQuery("FROM Class where section_id='"+user.getSection_id()+"'").list(); 
		         for (Iterator iterator = classes.iterator(); iterator.hasNext();){
		        	Class tempclass = (Class) iterator.next(); 
		            System.out.print("ClassId: " + tempclass.getClass_id()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return classes;
		   }
		   
		   /* Method to  READ the login details of particular class  */
		   public ClassUser getClassEmailIdByClassId(String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      ClassUser user = null;
		      
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("from ClassUser where class_id='"+classId+"'");
		          user = (ClassUser)query.uniqueResult();
		       
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return user;
		   }
		   
		   /* Method to get class from class common emailId  */
		   public ClassUser getClassByClassEmailId(String emailId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      ClassUser user = null;
		      
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("from ClassUser where email_id='"+emailId+"'");
		         user = (ClassUser)query.uniqueResult();
		       
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return user;
		   }
		   
		   /* Method to READ all the classes in which a teacher teaches */
		   public List<SubjectClass> listClassesByTeacherId(String teacherId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		    
		      List<SubjectClass> classList = new ArrayList<SubjectClass>();
		      List<SubjectTeacher> sub_teacherList = new ArrayList<SubjectTeacher>();
		      
		      AddTeacherService teacherService = new AddTeacherService();
		     
		      try{
		         tx = session.beginTransaction(); 
		         //tempSubjects = session.createSQLQuery("select subject_id FROM TBL_SUBJECT_TEACHER where teacher_id='"+teacherId+"'").list();
		         sub_teacherList = session.createQuery("FROM SubjectTeacher where teacher_id='"+teacherId+"'").list();
			
		       for(Iterator iterator =sub_teacherList.iterator(); iterator.hasNext();)
				{
					 SubjectTeacher sub=(SubjectTeacher)iterator.next();
					 String subject_id=sub.getSubject_id();
					 SQLQuery query=session.createSQLQuery("select class_id from tbl_subject_class where subject_id='"+subject_id+"'");
					 String class_id=(String) query.uniqueResult();
					 
					 int flag=0;
					 for(int i=0;i<classList.size();i++)
					 {
						 if(classList.get(i).getClass_id().equals(class_id))
							    flag++;
					 }
					 
					 if(flag==0)
						 classList.add(new SubjectClass(class_id));
				}
		       
		       
		       
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return classList;
		   }
}
